<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'m8:order:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="90%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #orderChildList>
        <a-button class="mb-2" @click="handleorderChildAdd" v-auth="'m8:order:edit'">
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
        <a-button class="mb-2 ml-2" @click="handleFormDr"  v-auth="'m8:order:edit'">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ '复制图纸' }}
        </a-button>
        <BasicTable @register="registerorderChildTable" @row-click="handleorderChildRowClick">
        </BasicTable>
      </template>
    </BasicForm>
    <InputForm @register="registerDrDrawer" @success="handleSuccess" />
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsM8OrderOrderForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner,useDrawer } from '/@/components/Drawer';
  import { Order, orderEditFormSave, orderEditForm } from '/@/api/m8/order/order';
  import { officeTreeData } from '/@/api/sys/office';
  import { basBasCusTreeData } from '/@/api/bas/cus/basCus';
  import { areaTreeData } from '/@/api/sys/area';
  import { BasicUpload } from '/@/components/Upload';
  import { WangEditor } from '/@/components/WangEditor';
  import InputForm from './formDr.vue';
  import { usePermission } from '/@/hooks/web/usePermission';
  const { hasPermission } = usePermission();

  // import { dateUtil, formatToDateTime } from '/@/utils/dateUtil';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('order.order');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<Order>({} as Order);

  const getTitle = computed(() => ({
    icon: meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增订单') : t('编辑订单'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('订单号'),
      field: 'ccode',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 200,
      },
      // required: true,
    },
    {
      label: t('客户简称'),
      field: 'cusCode',
      fieldLabel:'jgdw',
      component: 'TreeSelect',
      componentProps: {
        api: basBasCusTreeData,
        // params: { isLoadUser: true, userIdPrefix: '', isAll: true },
        allowClear: true,
      },
      required: true,
    },
    {
      label: t('下图日期'),
      field: 'xtdate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        showTime: false,
      },
      required: true,
    },
    {
      label: t('交付日期'),
      field: 'jfdate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        showTime: false,
      },
      required: true,
      // defaultValue: dateUtil(new Date()),
      // defaultValue: formatToDateTime(new Date()),
      // defaultValue: '2024-05-31',
    },
    {
      label: t('紧急程度'),
      field: 'jjlevel',
      component: 'RadioGroup',
      componentProps: {
        dictType: 'M8_order_level',
      },
    },
    {
      label: t('交付数量'),
      field: 'iqty',
      component: 'Input',
      componentProps: {
        maxlength: 200,
      },
    },
    {
      label: t('设计师'),
      field: 'designer',
      component: 'Input',
      componentProps: {
        maxlength: 200,
      },
    },
    {
      label: t('加工名称'),
      field: 'jgname',
      component: 'Input',
      componentProps: {
        maxlength: 200,
      },
    },
    {
      label: t('订单备注'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('图纸信息'),
      field: 'orderChildList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'orderChildList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerorderChildTable, orderChildTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'i-ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleorderChildDelete.bind(this, record),
          },
          auth: 'm8:order:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setorderChildTableData(_res: Recordable) {
    orderChildTable.setColumns([
      {
        title: t('图名'),
        dataIndex: 'picname',
        width: 200,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editRule: true,
      },
      {
        title: t('材料'),
        dataIndex: 'cmat',
        width: 100,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editRule: true,
      },
      {
        title: t('数量'),
        dataIndex: 'iqty',
        width: 80,
        align: 'left',
        editRow: true,
        editComponent: 'InputNumber',
        editRule: true,
        // editRule: [{ required: true }, { pattern: /^\d+$/, message: t('请输入一个正整数') }]
      },
      {
        title: t('单位'),
        dataIndex: 'cunit',
        width: 80,
        align: 'left',
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'sys_unit',
          allowClear: true,
        },
        editRule: true,
      },
      {
        title: t('单价'),
        dataIndex: 'fprice',
        width: 80,
        align: 'left',
        editRow: true,
        editComponent: 'InputNumber',
        ifShow: hasPermission(['pic:price:view']),
        // editRule: true,
      },
      {
        title: t('外部工艺'),
        dataIndex: 'outerRoute',
        width: 120,
        align: 'left',
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'm8_outer_route',
          mode: 'multiple',
          allowClear: true,
        },
        // editRule: true,
      },
      {
        title: t('图号'),
        dataIndex: 'picno',
        width: 100,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        // editRule: true,
      },
      {
        title: t('备注'),
        dataIndex: 'remarks',
        width: 100,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        // editRule: true,
      },
    ]);
    orderChildTable.setTableData(record.value.orderPicList || []);
  }

  function handleorderChildRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleorderChildAdd() {
    orderChildTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
      cunit:'件'
    });
  }

  function handleSuccess(selectData) {
    selectData.forEach((item) => {
        orderChildTable.insertTableDataRecord({
          ...item,
          isNewRecord: true,
          editable: true,
          cunit:'件'
        });
    });
  }

  function handleFormDr() {
    openDrawer(true, {});
  }

  function handleorderChildDelete(record: Recordable) {
    orderChildTable.deleteTableDataRecord(record);
  }

  async function getorderChildList() {
    let orderChildListValid = true;
    let orderChildList: Recordable[] = [];
    for (const record of orderChildTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        orderChildListValid = false;
      }
      orderChildList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of orderChildTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      orderChildList.push({
        ...record,
        status: '1',
      });
    }
    if (!orderChildListValid) {
      throw { errorFields: [{ name: ['orderChildList'] }] };
    }
    return orderChildList;
  }

  const [registerDrDrawer, { openDrawer }] = useDrawer();
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await orderEditForm(data);
    record.value = (res.m8Order || {}) as Order;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setorderChildTableData(res);
    // setorderChildTableData();
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.orderPicList = await getorderChildList();
      // console.log('submit', params, data, record);
      const res = await orderEditFormSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
